<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SecKillGoods extends Model
{
    protected $table = "seckillgoods";

    /**
     * @abstract append seckillgoods data to redis list
     * @param $id
     * @return bool
     */
    public static function addSecKillGoodsToRedisCache($id){
        $arrInfo = DB::select('select * from seckillgoods where id = ?',[$id]);
        $objSecKillGoods = array_shift($arrInfo);
        //首先测试列表的长度
        $length = Redis::llen('seckillgoods_'.$objSecKillGoods->id);
        $secKillGoodsCount = $objSecKillGoods->number_left - $length;
        for ($i = 0;$i < $secKillGoodsCount;$i++){
            Redis::lpush('seckillgoods_'.$objSecKillGoods->id,1);
        }
        $length = Redis::llen('seckillgoods_'.$objSecKillGoods->id);
        if($length == $objSecKillGoods->number_left){
            DB::update('update seckillgoods set status = 1 where id = ?',[$id]);
            return true;
        }else{
            return false;
        }
    }

    /**
     * @abstract buy seckillgoods process
     * @param $arrData
     * @return bool|string
     */
    public function buySecKillGoodsById($arrData){
        $count = Redis::lpop('seckillgoods_'.$arrData['id']);
        if(!$count){
            $logs = new logs();
            $logs->event = 'error no seckillgoods store ';
            $logs->type = 0;
            $logs->des = 'this id of seckillgoods is '.$arrData['id'];
            $logs->save();
            return false;
        }else{
            $order_sn = orders::build_order_no();
            $order = new orders();
            $order->order_sn = $order_sn;
            $order->weuser_id = $arrData['weuser_id'];
            $order->status = 1;
            $order->seckillgoods_id = $arrData['id'];
            $order->price = $arrData['price'];
            $order->save();

            $listLength = Redis::llen('seckillgoods_'.$arrData['id']);
            DB::update('update seckillgoods set number_left = ? where id = ?',[$listLength,$arrData['id']]);
            return $order_sn;
        }
    }



}
